package com.qingke.example;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qingke.pojo.User;

/**
 * Servlet implementation class UserListServlet
 */
@WebServlet("/UserListServlet")
public class UserListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private final String driver="com.mysql.jdbc.Driver";
	private final String url="jdbc:mysql://localhost:3306/web?useSSL=false";
	private final String u="root";
	private final String p="6775";

	private Connection conn = null;
	private String sql;
	private PreparedStatement ps = null;
	private ResultSet rs = null;
       
    public UserListServlet() {
        super();
    }
	public void init(ServletConfig config) throws ServletException {
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, u, p);
			System.out.println("conn:"+conn);
			System.out.println("Connect to database successfully!");
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		HashSet<String> usernames=(HashSet<String>)request.getServletContext().getAttribute("userList");
		if(usernames==null){
			usernames=new HashSet<String>();
		}
		String name=(String)request.getSession().getAttribute("currentUser");
		System.out.println("get username session for username");
		System.out.println(name);
		String nickname=getUserByUsername(name)==null?"":getUserByUsername(name).getName();
		String line= "me:"+nickname+",";
		
		for(String username:usernames){
			line += getUserByUsername(username).getName()+",";
		}
		line=line.equals("")?line:line.substring(0,line.length()-1);
		response.getWriter().println(line);
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	private User getUserByUsername(String username){
    	sql="select * from user where username=?";
    	User user=null;
    	try {
			ps=
					conn
					.prepareStatement(sql);
		    ps.setString(1,username);
		    rs=ps.executeQuery();
		    if(rs.next()){
		    	user=new User();
		    	user.setId(rs.getInt("id"));
		    	user.setUsername(rs.getString("username"));
		    	user.setPassword(rs.getString("password"));
		    	user.setName(rs.getString("name"));
		    }
		    return user;
		    
		} catch (SQLException e) {
			e.printStackTrace();
		}
    	return user;
    }
}
